package deanandjames.sprite;

import deanandjames.image.ImageLoader;
import deanandjames.ui.GamePanel;

import java.awt.*;

public class FireBallSprite extends Sprite {
	private static final int STEP = -10;
	private static final int STEP_OFFSET = 2;
	private final GamePanel gamePanel;
	private final Avatar jack;

	public FireBallSprite(int w, int h, ImageLoader imsLd, GamePanel jp, Avatar j) {
		super(w, h / 2, w, h, imsLd, "fireball");
		gamePanel = jp;
		jack = j;
		initPosition();
	}

	@Override
	public void updateSprite() {
		hasHitJack();
		goneOffScreen();
		super.updateSprite();
	}

	private int getRandRange(int x) {
		return (int) (2 * x * Math.random()) - x;
	}

	private void goneOffScreen() {
		if (locationX + getWidth() <= 0 && dx < 0) {
			initPosition();
		}
	}

	private void hasHitJack() {
		final Rectangle jackBox = jack.getMyRectangle();
		jackBox.grow(-jackBox.width / 3, 0);
		if (jackBox.intersects(getMyRectangle())) {
			gamePanel.showExplosion(locationX, locy + getHeight() / 2);
			initPosition();
		}
	}

	private void initPosition() {
		int h = getPanelHeight() / 2 + (int) (getPanelHeight() * Math.random()) / 2;
		if (h + getHeight() > getPanelHeight()) {
			h -= getHeight();
		}
		setPosition(getPanelWidth(), h);
		setStep(STEP + getRandRange(STEP_OFFSET), 0);
	}
}
